<?php
class gUser {
	static function register($data) {
		$r = uc_user_register($data['username'] , $data['password'] , $data['email']);
		if($r<=0) return $r;
		//TODO:register
	}

	public static $synlogin = '';
	public static function login($data = '') {
		if($data=='') $data = $_POST;
		list($uid, $username, $password) = self::uclogin($data);
		if($uid<=0) galaxy::gthrow(L("login_errno$uid"));
		$_ENV['g']->username = $username;
		$_ENV['g']->uid = $uid;
		self::writeAuth($uid, $username, $data['rememberme'] ? 8640000 : 0 );
		self::$synlogin = self::synlogin($uid);
		gSession::set('synlogin', self::$synlogin);
		gSession::set('footer_extra', self::$synlogin);
		return self::login_ok;
	}
	private static function uclogin($data) {
		require_cache(APP_PATH.'/Lib/uc_client/client.php');
		return uc_user_login($data['username'], $data['password']);
	}
	private static function writeAuth($uid, $username, $life = 0) {
		$life = intval($life);
		$life > 0 or $life = C('SESSION_EXPIRE');
		galaxy::gcookie('auth', galaxy::authcode("$uid\t$username\t$life", 'ENCODE'), $life);
		$S = D('session');
		if($S->where("uid=$uid")->count()) {
			$S->lastvisit = $_ENV['timestamp'];
			$S->onlineip = $_ENV['onlineip'];
			$S->save();
		} else {
			$data = array(
				'uid' => $uid,
				'username' => $username,
				'onlineip' => $_ENV['onlineip'],
				'lastvisit' => $_ENV['timestamp'],
			);
			$S->add($data);
		}
	}
	public static function auth($auth='') {
		!empty($auth) or $auth = galaxy::gcookie('auth');
		if(!empty($auth)) {
			list($uid, $username, $life) = explode("\t", galaxy::authcode( $auth, 'DECODE' ));
			self::writeAuth($uid, $username, $life);
		} else {
			$uid = $username = '';
		}
		return array($uid, $username);
	}
	public static function logout() {
		gSession::set('synlogin', null);
		self::destroyAuth($_ENV['g']->uid);
		$_ENV['g']->uid = $_ENV['g']->username = '';
	}
	private static function destroyAuth($uid) {
		galaxy::gcookie('auth', '', -1);
		$S = D('session');
		//TODO 异IP退出处理
		$S->where("uid=$uid")->delete();
	}
	public static function synlogin($uid) {
		require_cache(APP_PATH.'/Lib/uc_client/client.php');
		return uc_user_synlogin($uid);
	}
}
?>